/*oOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoO

Authors: Nitay Megides
		 Rachel Banino

Project: Exercise 1

Using: Hw1Types.h

Description:
A general module for general functions. Used throughout the project
oOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoO*/

#include "General.h"
#include "Logger.h"
#include <stdlib.h>

void TerminateProgram(int code)
{
    // Cleanup the logger to ensure writing
    LoggerCleanup();
    exit(code);
}

void AssertOutOfMemory(void* ptr)
{
    if (ptr == NULL) 
    { 
        LoggerWriteMessage("Error: Out of memory!\n");
        TerminateProgram(-1);
    }
}

void AssertFileOpenError(void* ptr)
{
    if (ptr == NULL) 
    { 
        LoggerWriteMessage("Error: File could not be opened\n");
        TerminateProgram(-2);
    }
}

void AssertFileError(BOOL bytesWritenEqualsBytesSent)
{
    if (!bytesWritenEqualsBytesSent) 
    { 
        LoggerWriteMessage("Error: Writing to file failed\n");
        TerminateProgram(-3);
    }
}

void AssertFileSizeError(int fileSize)
{
	if (fileSize < 0) 
    { 
        LoggerWriteMessage("Error: File size is invalid\n");
        TerminateProgram(-4);
    }
}

void AssertUser(void* user) 
{
    if (user == NULL)
    {
        printf("Invalid user ID");
        TerminateProgram(-5);
    }
}


void AssertProduct(void* product) 
{
    if (product == NULL)
    {
        printf("Invalid product ID");
        TerminateProgram(-6);
    }
}

void WriteAndAssert(FILE* file, void* data, size_t size)
{
    AssertFileError(fwrite(data, 1, size, file) == size);
}

void ReadAndAssert(FILE* file, void* buffer, size_t size)
{
    AssertFileError(fread(buffer, 1, size, file) == size);
}
